package com.chery.media.library.extend

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.google.gson.JsonParser
import java.util.ArrayList
import java.util.regex.Pattern

/**
 * 是否为手机号  0开头 12开头的不支持
 */
fun String?.isPhone(): Boolean {
    return this?.let {
        Pattern.matches(it, "0?(13|14|15|16|17|18|19)[0-9]{9}")
    }?:let {
       false
    }
}

/**
 * 是否为座机号
 */
fun String?.isTel(): Boolean {
    return this?.let {
        val matcher1 = Pattern.matches("^0(10|2[0-5|789]|[3-9]\\d{2})\\d{7,8}\$", this)
        val matcher2 = Pattern.matches("^0(10|2[0-5|789]|[3-9]\\d{2})-\\d{7,8}$", this)
        val matcher3 = Pattern.matches("^400\\d{7,8}$", this)
        val matcher4 = Pattern.matches("^400-\\d{7,8}$", this)
        val matcher5 = Pattern.matches("^800\\d{7,8}$", this)
        val matcher6 = Pattern.matches("^800-\\d{7,8}$", this)
        return matcher1 || matcher2 || matcher3 || matcher4 || matcher5 || matcher6
    }?:let {
        false
    }
}

/**
 * 是否为邮箱号
 */
fun String?.isEmail(): Boolean {
    return this?.let {
        Pattern.matches(this, "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$")
    }?:let {
        false
    }
}

fun String?.toIntegerString(): String {
    return this?.let {
        it.split(".")[0].replace("[^0-9]*".toRegex(), "")
    }?:"0"
}

/**
 * 小于10前面补0
 */
fun Int.fillIn(): String = if (this < 10) "0$this" else "$this"

/**
 * 将对象转为JSON字符串
 */
fun Any?.toJson():String{
    return Gson().toJson(this)
}

//转换成时间字符串
fun Long?.toTime10String(pattern: String = "yyyy-MM-dd"): String = TimeUtils.millis2String((this?: 0L) * 1000, pattern)

//转换成时间字符串
fun Long?.toTime13String(pattern: String = "yyyy-MM-dd"): String = TimeUtils.millis2String((this?: 0L), pattern)

fun String?.toTime10String(pattern: String = "yyyy-MM-dd"): String = TimeUtils.millis2String("${this}000".toLong(), pattern)

fun String?.toTime13String(pattern: String = "yyyy-MM-dd"): String = TimeUtils.millis2String("$this".toLong(), pattern)

//fun String?.toTime(): String {
//    if (this.isNullOrEmpty()) {
//        return "00:00"
//    } else {
//        val time = this.toInt() / 1000
//        val time / 60
//    }
//    return ""
//}

/**
 * 将毫秒值字符串转为分秒
 */
fun String?.toTime(): String {
    return if (this.isNullOrEmpty()) {
        "00:00"
    } else {
        val time = this.toLong() / 1000
        val minute = time / 60
        val second = time % 60
        "${minute.toInt().fillIn()}:${second.toInt().fillIn()}"
    }
}

/**
 * 将json转为对象
 */
fun <T> String.jsonToObject(cls: Class<T>): T = GsonUtils.fromJson(this, cls)

/**
 * 将json转为list
 */
fun <T> String?.jsonToList(cls: Class<T>?): MutableList<T> {
    val gson = Gson()
    val list: MutableList<T> = ArrayList()
    val array = JsonParser().parse(this).asJsonArray
    for (elem in array) {
        list.add(gson.fromJson(elem, cls))
    }
    return list
}
